package com.hunan.api.catv.service.biz.member.login;

import cn.hutool.core.date.DateUtil;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.LoginType;
import com.hunan.api.catv.entity.po.Member;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.entity.vo.login.jiguang.JiGuangLoginResVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.member.LoginService;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.toupiao.TouPiaoBiz;
import com.hunan.api.catv.service.impl.member.MemberService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RSAUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class OneKeyLoginService extends ResultService implements LoginService {

    @Value("${login.jiguang.appKey}")
    private String JG_APP_KEY;

    @Value("${login.jiguang.masterSecret}")
    private String JG_MASTER_SECRET;

    @Value("${rsa.privateKey}")
    private String RSA_PRIVATE_KEY;

    @Value("${login.jiguang.url}")
    private String LOGIN_URL;

    @Autowired
    private RestTemplate baseRestTemplate;

    @Autowired
    private MemberBiz memberBiz;

    @Autowired
    private MemberService memberService;

    @Autowired
    TouPiaoBiz touPiaoBiz;

    @Override
    public ServiceResult login(String id, String phone, String sms, String ip, String pushToken, String... extParams) {
        if (null == extParams || extParams.length == 0 || null == extParams[0]) {
            return buildFail("一键登录jgLoginToken为空，请重试！");
        } else {
            /*HttpServletRequest request = getServletRequest();
            String c = request.getHeader("c");
            byte[] bytes = null;
            if (c != null) {
                switch (c) {
                    case "1":
                        bytes = (JG_APP_KEY + ":" + JG_MASTER_SECRET).getBytes(StandardCharsets.UTF_8);
                        break;
                    case "4":
                        bytes = ("edbda906d778e5a10a097d20" + ":" + "c5434b7f5224f476c4959107").getBytes(StandardCharsets.UTF_8);
                        break;
                }
            }*/
            byte[] bytes = (JG_APP_KEY + ":" + JG_MASTER_SECRET).getBytes(StandardCharsets.UTF_8);
            String jgLoginToken = extParams[0];
            //byte[] bytes = (JG_APP_KEY + ":" + JG_MASTER_SECRET).getBytes(StandardCharsets.UTF_8);
            String authorizationStr = Base64.getEncoder().encodeToString(bytes);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Basic " + authorizationStr);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE);
            //MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            Map<String, Object> postParameters = new HashMap<String, Object>();
            postParameters.put("loginToken", jgLoginToken);
            //postParameters.add("loginToken", jgLoginToken);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<>(postParameters, headers);
            JiGuangLoginResVo res = null;
            try {
                res = baseRestTemplate.postForEntity(LOGIN_URL, formEntity, JiGuangLoginResVo.class).getBody();
            } catch (Exception e) {
                log.error("调用极光一键登录远程校验接口出错：", e);
                return buildFail(false, ConstantsMsg.jiguang_auth_remote_fail);
            }

            if (null != res) {
                if (res.getCode() == 8000) {
                    MemberVo memberVo = null;
                    try {
                        res.setPhone(RSAUtils.decrypt(res.getPhone(), RSA_PRIVATE_KEY));
                        phone = res.getPhone();
                        memberVo = memberBiz.getByPhone(phone);
                        if (ObjectUtils.isEmpty(memberVo)) {
                            ServiceResult registerResult = memberBiz.register(LoginType.jiguang.getCode(), null, phone, null, null, null, ip, pushToken);
                            if (!registerResult.getStatus()) {
                                return registerResult;
                            }
                            memberVo = memberBiz.getByPhone(phone);
                        }
                    } catch (Exception e) {
                        return buildFail(res, "RSA解密极光返回的手机号码失败");
                    }
                    JsonObject memberJson = new JsonObject();
                    memberJson.addProperty("member", GsonUtils.toJson(memberVo));
                    memberJson.addProperty("isBind", false);
                    if (0 != memberVo.getInviter() && 1 == memberVo.getInviteesStatus()) {
                        Member member = new Member();
                        member.setInviteesStatus(2);
                        member.setMemberId(memberVo.getMemberId());
                        member.setLastLoginTime(new Date());
                        member.setFirstLoginTime(StringUtils.isBlank(DateUtil.formatDateTime(memberVo.getLastLoginTime())) ? new Date() : memberVo.getFirstLoginTime());
                        ServiceResult updateResult = memberService.update(member);
                        if (!updateResult.getStatus()) {
                            return updateResult;
                        }
                        touPiaoBiz.addTicketToUser(memberVo.getInviter(), 2);
                    }
                    return buildOK(memberJson, "极光一键登录校验成功");
                } else {
                    return buildFail(res, "极光一键登录校验接口返回校验失败");
                }

            }
        }
        return buildFail(false, ConstantsMsg.jiguang_auth_fail);
    }


    @Override
    public ServiceResult bind(String id, Integer loginType, Integer memberId) {
        return null;
    }
}
